package cn.work100.modular.layuiMsn.layimUserAdmin;
import cn.hutool.json.JSONArray;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.work100.core.common.constant.DefaultAvatar;
import cn.work100.core.shiro.ShiroKit;
import cn.work100.modular.layuiMsn.dataControl.service.LayimGroupService;
import cn.work100.modular.layuiMsn.dataControl.service.LayimUserFriendService;
import cn.work100.modular.layuiMsn.entity.*;
import cn.work100.modular.layuiMsn.entity.db.LayimGroup;
import cn.work100.modular.layuiMsn.entity.db.LayimUserFriend;
import cn.work100.modular.system.entity.FileInfo;
import cn.work100.modular.system.entity.User;
import cn.work100.modular.system.service.FileInfoService;
import cn.work100.modular.system.service.UserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserService userService;

    @Resource
    private FileInfoService fileInfoService;

    @Resource
    private LayimUserFriendService layimUserFriendService;

    @Resource
    private LayimGroupService layimGroupService;

    @RequestMapping("/getUserInfo")
    private JSONObject getUserInfo(){
        User o = (User) redisTemplate.opsForValue().get(ShiroKit.getUserNotNull().getAccount());
        List<User> userInfoAll = userService.list();
        // 设置返回参数
        LayimData layimData = new LayimData();
        layimData.setCode(0);
        layimData.setMsg("请求失败，请联系管理员");
        // 设置我的信息
        LayimMine layimMine = new LayimMine();
        layimMine.setUsername(o.getName());
        layimMine.setSign(o.getRemark());
        layimMine.setStatus("online");
        layimMine.setAvatar(previewAvatar(o.getUserId()));
        layimMine.setId(o.getUserId());
        // 获取所有在线用户
        Map<Object,Object> userList = (Map<Object,Object>) redisTemplate.opsForValue().get("onlineUserList");
        // 获取当前用户的好友列表
        LayimUserFriend layimUserFriend = (LayimUserFriend) redisTemplate.opsForValue().get("friend"+o.getAccount());
        if (layimUserFriend == null){
            QueryWrapper<LayimUserFriend> layimUserFriend1 = new QueryWrapper<>();
            layimUserFriend1.eq("userId",o.getUserId());
            layimUserFriend = layimUserFriendService.getOne(layimUserFriend1);
            if (layimUserFriend != null)
            redisTemplate.opsForValue().set("friend"+o.getAccount(),layimUserFriend);
        }
        // layimUserFriend.getFriendId() 的格式应是{ userid : xx,groupid:xxx}
        JSONArray jsonArray = new JSONArray(layimUserFriend == null ? "[]":layimUserFriend.getFriendId());
        // 查询账号分组
        List<LayimGroup> groupList = (List<LayimGroup>) redisTemplate.opsForValue().get("group"+o.getAccount());
        if (groupList == null ) {
            QueryWrapper<LayimGroup> groupQueryWrapper = new QueryWrapper<>();
            groupQueryWrapper.eq("userId", o.getUserId());
            groupList = layimGroupService.list(groupQueryWrapper);
            if (groupList != null)
                redisTemplate.opsForValue().set("group"+o.getAccount(),groupList);
        }
        // 创建好友集合和设置好友分组
        List<LayimFriend> layimFriends = new ArrayList<>();
        if (groupList.size() > 0){
            // 获取用户分组
            for (LayimGroup lg : groupList){
                LayimFriend layimFriend = new LayimFriend();
                layimFriend.setGroupname(lg.getGroup());
                layimFriend.setId(lg.getId());
                layimFriend.setOnline(0);
                // 设置好友分组
                List<UserTo> userToslist = new ArrayList<>();
                // 获取用户好友ID
                for (Object jsonObject : jsonArray){
                    cn.hutool.json.JSONObject object = (cn.hutool.json.JSONObject) jsonObject;
                    // 判断好友的分组信息
                    if (object.getLong("groupid") == lg.getId()){
                        UserTo userTo = new UserTo();
                        boolean falg = userList.containsKey(String.valueOf(object.get("userid")));
                        User userid = userService.getById(object.getLong("userid"));
                        userTo.setUsername(userid.getName());
                        userTo.setId(userid.getUserId());
                        userTo.setAvatar(previewAvatar(userid.getUserId()));
                        userTo.setSign(userid.getRemark());
                        userTo.setStatus(falg ? "online":"offline");
                        userToslist.add(userTo);
                    }
                }
                if (userToslist != null)
                    Collections.sort(userToslist, new Comparator<UserTo>() {
                        @Override
                        public int compare(UserTo o1, UserTo o2) {
                            if (o1.getStatus().length() > o2.getStatus().length()) {
                                return 1;
                            } else if (o1.getStatus().length() == o2.getStatus().length()) {
                                return 0;
                            } else {
                                return -1;
                            }
                        }
                    });
                layimFriend.setList(userToslist);
                layimFriends.add(layimFriend);
            }
        } else {
            LayimGroup layimGroup = new LayimGroup();
            layimGroup.setGroup("我的好友");
            layimGroup.setUserId(o.getUserId());
            layimGroupService.insert(layimGroup);

            LayimFriend layimFriend = new LayimFriend();
            layimFriend.setGroupname("我的好友");
            layimFriend.setId(layimGroup.getId());
            layimFriend.setList(null);
            layimFriend.setOnline(0);
            layimFriends.add(layimFriend);
        }
        // 设置群聊
        LayimGroup layimGroup = new LayimGroup();
        // 包装返回的data
        LayimAllData layimAllData = new LayimAllData();
        // 设置好友信息
        layimAllData.setFriend(layimFriends);
        // 设置群组信息
        layimAllData.setGroup(null);
        // 设置我的信息
        layimAllData.setMine(layimMine);
        // 设置返回参数 data
        layimData.setData(layimAllData);
        return JSON.parseObject(JSON.toJSONString(layimData));
    }

    // 获取用户头像
    public String previewAvatar(Long userid){
        User user = userService.getById(userid);
        String avatar = user.getAvatar();
        //如果头像id为空就返回默认的
        if (ToolUtil.isEmpty(avatar)) {
            avatar = DefaultAvatar.BASE_64_AVATAR;
        } else {
            FileInfo fileInfo = fileInfoService.getById(avatar);
            if (fileInfo == null) {
                avatar = DefaultAvatar.BASE_64_AVATAR;
            } else {
                avatar = fileInfo.getFileData();
            }
        }
        return "data:image/jpeg;base64,"+avatar;
    }
}
